package sddz.foodmanage.fragment;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.asm.Type;
import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.activity.CreationFoodActivity;
import sddz.foodmanage.activity.LoginActivity;
import sddz.foodmanage.adapter.OrderAdapter;
import sddz.foodmanage.adapter.OrderSparseadpter;
import sddz.foodmanage.adapter.RecyclerAdapter;
import sddz.foodmanage.base.BaseFragment;
import sddz.foodmanage.dialog.ImagePreviewDialog;
import sddz.foodmanage.model.CommodityBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.DoubleUtil;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.MyUtils;
import sddz.foodmanage.utils.SpfUtils;
import sddz.foodmanage.view.MyListView;

import static android.app.Activity.RESULT_OK;

/**
 * /**
 *
 * @Date:2019/7/3
 * @Author:lbb 商品列表
 */
public class CommoditylistFragment extends BaseFragment implements OrderSparseadpter.ModifyCountInterface {
    public static final String TAG = "MyFragment";
    Unbinder unbinder;
    TwinklingRefreshLayout newsTrl;
    MyListView shangpinlist;
    TextView tvNodata;
    private int str;
    private int pages = 1;
    View view;
    CommodityBean commoditybean;
    private OrderSparseadpter adapter = new OrderSparseadpter();
    private List<CommodityBean.DataBeanX.DataBean> list = new ArrayList<>();
//    private List<CommodityBean.DataBeanX.DataBean> xuanzhonglist = new ArrayList(new HashSet());
    private ImagePreviewDialog previewDialog;
    private List<String> imageList = new ArrayList<>();
    SparseArray<CommodityBean.DataBeanX.DataBean> goodslist = new SparseArray<CommodityBean.DataBeanX.DataBean>();//用来存放商品数据

    public CommoditylistFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_commoditylist, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initData();
        initListener();
        view.setClickable(true);
        return view;
    }

    private void initData() {
        searchsp(str,pages);
    }

    private void initView() {
        shangpinlist = view.findViewById(R.id.shangpinlist);
        tvNodata = view.findViewById(R.id.tv_nodata);
        newsTrl = view.findViewById(R.id.news_trl);
        ProgressLayout progressLayout = new ProgressLayout(mActivity);
        progressLayout.setColorSchemeResources(R.color.colorPrimary);
        newsTrl.setHeaderView(progressLayout);

        //得到数据id
        str = getArguments().getInt(TAG);
        Log.e("得到的数据",str+"");

    }

    private void initListener() {
        newsTrl.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
               pages=1;
                searchsp(str,pages);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                pages++;
                searchsp(str,pages);
            }
        });
        if (adapter != null) {
            adapter.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
        }

    }
    //获取商品
    private void searchsp(final int str, final int pages) {
//        Log.e("str+pages",str+","+pages+"");
        Map<String, String> params = new HashMap<>();
        params.put("current_page", pages + "");
        params.put("page_size", "10");
        params.put("name", "");
        params.put("classification_id", str + "");
//        Log.e("params", JSON.toJSONString(params));
           String url=API.getcommoditylist;
//        baseDialog.show();
        HttpUtils.getInstance().POST(mActivity,url,JSON.toJSONString(params), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
//                baseDialog.dismiss();
                Log.e("搜索结果：", body);
                if(pages==1){
                    list.clear();
                    newsTrl.finishRefreshing();
                }else{
                    newsTrl.finishLoadmore();
                }
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
                        if (code == 200) {
                            if (jsonObject.optJSONObject("data") != null) {
                                commoditybean = new Gson().fromJson(body, CommodityBean.class);
                                if (commoditybean.getData().getData() != null&&commoditybean.getData().getTotal()>0) {
                                     List<CommodityBean.DataBeanX.DataBean> list2 = new ArrayList<>();
                                    list.addAll(commoditybean.getData().getData());
                                    //判断是否是供应商，如果是供应商，根据status这个值为1，显示未上架图标
                                    if (SpfUtils.getUserData(mActivity).getType() != 3) {
                                        for (int a = 0; a < list.size(); a++) {
                                            if (list.get(a).getStatus() == 1) {
                                                list2.add(list.get(a));
                                            }

                                        }
                                        list.clear();
                                        list.addAll(list2);
                                    }
                                    if(list.size()>0) {
                                        for(int a=0;a<list.size();a++){
                                            String key=str+list.get(a).getId()+"";
                                           if(HomeFragment.changelist.get(Integer.parseInt(key))!=null) {
                                               goodslist.put(Integer.parseInt(key), HomeFragment.changelist.get(Integer.parseInt(key)));
                                           }else{
                                               goodslist.put(Integer.parseInt(key),list.get(a));
                                           }
                                        }
                                        if (goodslist.size() > 0) {
                                            adapter.setdata(mActivity, goodslist, SpfUtils.getUserData(mActivity).getType());
                                            tvNodata.setVisibility(View.GONE);
                                            shangpinlist.setVisibility(View.VISIBLE);
                                            shangpinlist.setAdapter(adapter);
                                        } else {
                                            tvNodata.setVisibility(View.VISIBLE);
                                            shangpinlist.setVisibility(View.GONE);
                                        }
                                        adapter.notifyDataSetChanged();
                                    } else{
                                        show("没有更多数据了");
                                        }

                                }else{
                                    show("没有更多数据了");
                                }
                            }

                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            searchsp(str,1);
                        } else if (code == 401) {
                            show(jsonObject.optString("message"));
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            mActivity.finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Request error, Exception e) {
//                baseDialog.dismiss();
                show("访问数据失败，请稍后重试");
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==2&&resultCode==RESULT_OK){//修改页面返回的，需要刷新数据
//            Log.e("onActivityResult修改页面返回的","修改页面返回的");
            searchsp(str,pages);
        }
    }

    /**
     * 点击加号
     * @param showCountView 用于展示变化后数量的View
     * @param position
     */
    public void doIncrease(final View showCountView, final int position) {
        Log.e("jia", ((TextView)showCountView).getText().toString());
        final String numStr = ((TextView) showCountView).getText().toString().trim();
        Double add= DoubleUtil.add(Double.parseDouble(((TextView)showCountView).getText().toString()),Double.parseDouble("1"));
        ((TextView)showCountView).setText(add + "");
       int goodid= goodslist.get(goodslist.keyAt(position)).getId();
        if(HomeFragment.changelist!=null) {
            if (HomeFragment.changelist.size() > 0) {
                for (int aa = 0; aa < HomeFragment.changelist.size(); aa++) {
                    int changeid = HomeFragment.changelist.get(HomeFragment.changelist.keyAt(aa)).getId();
                    if (changeid == goodid) {//修改的集合中有当前商品信息,吧新的数量存起来
                        HomeFragment.changelist.get(HomeFragment.changelist.keyAt(aa)).setNum(((TextView) showCountView).getText().toString());
                    } else {
                        goodslist.get(goodslist.keyAt(position)).setNum(((TextView) showCountView).getText().toString().trim());
                        HomeFragment.changelist.put(goodslist.keyAt(position), goodslist.get(goodslist.keyAt(position)));
                    }
                }
            } else {
                goodslist.get(goodslist.keyAt(position)).setNum(((TextView) showCountView).getText().toString().trim());
                HomeFragment.changelist.put(goodslist.keyAt(position), goodslist.get(goodslist.keyAt(position)));
            }
        }
    }

    @Override
    public void doDecrease(final View showCountView, final int position) {
                Double currentCount = Double.parseDouble(((TextView) showCountView).getText().toString());
                if (currentCount == 0.0) {
                    int goodid= goodslist.get(goodslist.keyAt(position)).getId();
                    if(HomeFragment.changelist!=null) {
                        if (HomeFragment.changelist.size() > 0) {
                            for (int aa = 0; aa < HomeFragment.changelist.size(); aa++) {
                                int changeid = HomeFragment.changelist.get(HomeFragment.changelist.keyAt(aa)).getId();
                                if (changeid == goodid) {//修改的集合中有当前商品信息,吧新的数量存起来
                                    HomeFragment.changelist.remove(HomeFragment.changelist.keyAt(aa));
                                }
                            }
                        }
                    }
                    return;
                }
                if (currentCount < 1.0) {
                    ((TextView) showCountView).setText(0 + "");
                    int goodid= goodslist.get(goodslist.keyAt(position)).getId();
                    if(HomeFragment.changelist!=null) {
                        if (HomeFragment.changelist.size() > 0) {
                            for (int aa = 0; aa < HomeFragment.changelist.size(); aa++) {
                                int changeid = HomeFragment.changelist.get(HomeFragment.changelist.keyAt(aa)).getId();
                                if (changeid == goodid) {//修改的集合中有当前商品信息,吧新的数量存起来
                                    HomeFragment.changelist.remove(HomeFragment.changelist.keyAt(aa));
                                }
                            }
                        }
                    }
                    return;
                }
        Double jian = DoubleUtil.sub(Double.parseDouble(((TextView) showCountView).getText().toString()), Double.parseDouble("1"));
        ((TextView) showCountView).setText(jian + "");
        int goodid= goodslist.get(goodslist.keyAt(position)).getId();
        if(HomeFragment.changelist!=null) {
            if (HomeFragment.changelist.size() > 0) {
                for (int aa = 0; aa < HomeFragment.changelist.size(); aa++) {
                    int changeid = HomeFragment.changelist.get(HomeFragment.changelist.keyAt(aa)).getId();
                    if (changeid == goodid) {//修改的集合中有当前商品信息,吧新的数量存起来
                        HomeFragment.changelist.get(HomeFragment.changelist.keyAt(aa)).setNum(((TextView) showCountView).getText().toString().trim());
                    }else{
                        goodslist.get(goodslist.keyAt(position)).setNum(((TextView) showCountView).getText().toString().trim());
                        HomeFragment.changelist.put(goodslist.keyAt(position),goodslist.get(goodslist.keyAt(position)));
                    }
                }
            }
        }
    }

    @Override
    public void doTextView(final View showCountView, final int position) {
                final EditText inputServer = new EditText(mActivity);
                inputServer.setHint("请输入重量");
                inputServer.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                inputServer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                builder.setView(inputServer)
                        .setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (TextUtils.isEmpty(inputServer.getText().toString()) || inputServer.getText().toString().equals("0")) {//如果数量 为0，移除数据
                            ((TextView) showCountView).setText("0");
                            int goodid= goodslist.get(goodslist.keyAt(position)).getId();
                            if(HomeFragment.changelist!=null) {
                                if (HomeFragment.changelist.size() > 0) {
                                    for (int aa = 0; aa < HomeFragment.changelist.size(); aa++) {
                                        int changeid = HomeFragment.changelist.get(HomeFragment.changelist.keyAt(aa)).getId();
                                        if (changeid == goodid) {//修改的集合中有当前商品信息,吧新的数量存起来
                                            HomeFragment.changelist.remove(HomeFragment.changelist.keyAt(aa));
                                        }
                                    }
                                }
                            }
                            return;
                        }
                        if (MyUtils.isDoubleOrFloat(inputServer.getText().toString())) {
                            String result = String.format("%.1f", Double.parseDouble(inputServer.getText().toString()));
                            ((TextView) showCountView).setText(result);
                            int goodid= goodslist.get(goodslist.keyAt(position)).getId();
                            if(HomeFragment.changelist!=null) {
                                if (HomeFragment.changelist.size() > 0) {
                                    for (int aa = 0; aa < HomeFragment.changelist.size(); aa++) {
                                        int changeid = HomeFragment.changelist.get(HomeFragment.changelist.keyAt(aa)).getId();
                                        if (changeid != goodid) {//修改的集合中有当前商品信息,吧新的数量存起来
                                            goodslist.get(goodslist.keyAt(position)).setNum(((TextView) showCountView).getText().toString().trim());
                                            HomeFragment.changelist.put(goodslist.keyAt(position), goodslist.get(goodslist.keyAt(position)));
                                        }
                                    }
                                } else {
                                    goodslist.get(goodslist.keyAt(position)).setNum(((TextView) showCountView).getText().toString().trim());
                                    HomeFragment.changelist.put(goodslist.keyAt(position), goodslist.get(goodslist.keyAt(position)));
                                }
                            }
                        } else {
                            ((TextView) showCountView).setText("0");//输入的数量不是double类型的，也默认为0，移除数据
                            int goodid= goodslist.get(goodslist.keyAt(position)).getId();
                            if(HomeFragment.changelist!=null) {
                                if (HomeFragment.changelist.size() > 0) {
                                    for (int aa = 0; aa < HomeFragment.changelist.size(); aa++) {
                                        int changeid = HomeFragment.changelist.get(HomeFragment.changelist.keyAt(aa)).getId();
                                        if (changeid == goodid) {//修改的集合中有当前商品信息,吧新的数量存起来
                                            HomeFragment.changelist.remove(HomeFragment.changelist.keyAt(aa));
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
                builder.show();

    }

    @Override
    public void dochange(View showCountView, int position) {
        startActivityForResult(new Intent(mActivity, CreationFoodActivity.class).putExtra("status","false")
                .putExtra("listdata",list.get(position)),2);
    }

    @Override
    public void dodatu(View showCountView, int position) {
        if(SpfUtils.getUserData(mActivity).getType()==2) {
            List<CommodityBean.DataBeanX.DataBean.ImgsBean> imlist = list.get(position).getImgs();
            if (imageList != null) {
                imageList.clear();
            }
            for (int a = 0; a < imlist.size(); a++) {
                imageList.add(imlist.get(a).getUrl());
                Log.e("imageListurl", imlist.get(a).getUrl());
            }
            previewDialog = new ImagePreviewDialog(mActivity);
            previewDialog.setData(imageList);
            previewDialog.showDialog(shangpinlist);
        }
    }





    }
